package com.my.study.io.reader;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author Carlos
 * @version 1.0
 * @Description 处理流测试
 *
 * 关闭的话，只需要关闭外层流。
 *
 * @date 2021/6/27 8:28
 **/
@Slf4j(topic = "c.BufferedReaderTest")
public class BufferedReaderTest {

    public static void main(String[] args) {
        String path = "D:/file/a.txt";
        test_(path);


    }

    private static void test_(String path) {
        String line;
        StringBuilder sb = new StringBuilder();

        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(path));
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                sb.append(line).append("\n");
            }
            System.out.println(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void test_try(String path) {
        String line;
        StringBuilder sb = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(
                new FileReader(path))) {
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                sb.append(line).append("\n");
            }
            System.out.println(sb.toString());
        } catch (IOException e) {
            log.error("读取错误", e);
        }
    }

}
